/*
 *  Program looks for the pairs of neighboring numbers in array of integers provided by user;
 *  Result returned is a pair which places in array are on a minimum distance;
 *  
 *  PS: its a result of misinterpreted task - JavaBasic task implementation is provided in NeighboringNumbers
 */

import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;

public class ArrayNeighbouringNumbers {

	public static void main(String[] args) throws NumberFormatException,
			IOException {
		Scanner in = new Scanner(System.in);
		System.out.println("Set the lenght of your array: ");
		int length = in.nextInt();
		int userArray[] = new int[length];
		System.out.println("Fill your array with " + length + " int values: ");

		Map<Integer, Integer> unsortedMap = new HashMap<Integer, Integer>();
		for (int i = 0; i < userArray.length; i++) {
			userArray[i] = in.nextInt();
			unsortedMap.put(i, userArray[i]);
		}

		System.out.println("Entered Data......");
		for (Map.Entry entry : unsortedMap.entrySet()) {
			System.out.println("Index : " + entry.getKey() + " Value : "
					+ entry.getValue());
		}

		Iterator iterator = unsortedMap.entrySet().iterator();
		Map<Integer, Integer> sortedMap = sortByValues(unsortedMap);
		Integer[] keys = sortedMap.keySet().toArray(
				new Integer[userArray.length]);
		Integer[] values = sortedMap.values().toArray(
				new Integer[userArray.length]);
		int index = 0;
		boolean PairExists = false;
		int minDistance = userArray.length - 1;

		for (int i = 0; i < userArray.length - 1; i++) {
			if (values[i + 1] - values[i] == 1) {
				PairExists = true;
				if (Math.abs(keys[i + 1] - keys[i]) < minDistance) {
					minDistance = Math.abs(keys[i + 1] - keys[i]);
					index = i;
				}
			}
		}

		if (PairExists) {
			System.out.println(" neigbouring pair with minimal distance ["
					+ minDistance + " numbers] is: " + values[index] + ", "
					+ values[index + 1]);
			System.out.println("index of first entered number in pair is: "
					+ Math.min(keys[index], keys[index + 1]));
		} else {
			System.out.println("array has no neighbouring numbers");
		}
	}

	public static Map sortByValues(Map unsortedMap) {
		List list = new LinkedList(unsortedMap.entrySet());

		Collections.sort(list, new Comparator() {
			public int compare(Object o1, Object o2) {
				return ((Comparable) ((Map.Entry) (o1)).getValue())
						.compareTo(((Map.Entry) (o2)).getValue());
			}
		});

		Map sortedMap = new LinkedHashMap();
		for (Iterator it = list.iterator(); it.hasNext();) {
			Map.Entry entry = (Map.Entry) it.next();
			sortedMap.put(entry.getKey(), entry.getValue());
		}
		return sortedMap;
	}
}
